"use client";

import { useState, useEffect } from "react";
import { Button, Input, message, Checkbox, Form } from "antd";
import { LockOutlined, PhoneOutlined } from "@ant-design/icons";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { userCenterRequestSms, userCenterLogin } from "@/apis";

export default function Login() {
  const [form] = Form.useForm();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [smsLoading, setSmsLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [agreed, setAgreed] = useState(false);

  // 倒计时效果
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  // 发送短信验证码
  const handleSendSms = async () => {
    try {
      const mobile = form.getFieldValue("mobile");
      if (!mobile) {
        message.error("请先输入手机号");
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(mobile)) {
        message.error("请输入正确的手机号");
        return;
      }

      setSmsLoading(true);

      // 调用发送短信API
      const response = await userCenterRequestSms({
        baseURL: "/api/proxy",
        query: {
          mobile: mobile,
        },
      });

      if (response.data?.success) {
        message.success("验证码已发送");
        setCountdown(60);
      } else {
        message.error(response.data?.message || "发送验证码失败");
      }
    } catch (error) {
      console.error("发送验证码失败:", error);
      message.error("发送验证码失败，请稍后重试");
    } finally {
      setSmsLoading(false);
    }
  };

  // 登录处理
  const handleLogin = async () => {
    if (!agreed) {
      message.error("请先同意用户协议和隐私政策");
      return;
    }

    try {
      setLoading(true);

      // 获取表单数据
      const values = await form.validateFields();

      // 调用登录API - 使用 userCenterLogin (短信验证码登录)
      const response = await userCenterLogin({
        baseURL: "/api/proxy",
        body: {
          mobile: values.mobile,
          code: values.code,
        },
      });

      // 如果登录成功，尝试获取JWT token
      if (response.data?.success) {
        const userData = response.data.data;
        console.log("Login response data:", response.data);
        console.log("User data:", userData);

        // 检查是否有JWT token
        if (userData?.token && userData.token.startsWith("eyJ")) {
          console.log("Found JWT token:", userData.token);
        } else {
          console.log("No JWT token found in response");
          console.log(
            "userData keys:",
            userData ? Object.keys(userData) : "undefined"
          );
          console.log("userData values:", userData);
          console.log("Token type:", typeof userData?.token);
          console.log("Token value:", userData?.token);

          // 生成正确格式的token，模仿成功的请求
          if (userData?.token && userData?.id) {
            console.log("生成正确格式的token...");
            console.log("UUID token:", userData.token);
            console.log("User ID:", userData.id);

            // 创建正确格式的payload，模仿成功的请求
            const payload = {
              Token: userData.token, // 使用真实的UUID token
              userId: userData.id,
            };

            console.log("Payload before encoding:", payload);

            // 使用Base64编码，就像成功的请求一样
            const encodedPayload = btoa(JSON.stringify(payload));

            console.log("Generated correct format token:", encodedPayload);
            console.log("Payload:", payload);

            // 使用生成的正确格式token
            userData.token = encodedPayload;
          } else {
            console.log("无法生成正确格式token：缺少必要信息");
          }
        }
      }

      if (response.data?.success) {
        // 登录成功，保存用户信息到localStorage
        const userData = response.data.data;
        console.log("Login response data:", response.data);
        console.log("User data:", userData);

        if (userData) {
          localStorage.setItem("userInfo", JSON.stringify(userData));
          localStorage.setItem("token", userData.token || "");

          // 触发自定义事件，通知其他组件用户信息已更新
          window.dispatchEvent(new CustomEvent("userInfoChanged"));
        }

        message.success("登录成功");
        router.push("/");
      } else {
        message.error(
          response.data?.message || "登录失败，请检查验证码是否正确"
        );
      }
    } catch (error) {
      console.error("登录失败:", error);
      if (error instanceof Error) {
        message.error(error.message);
      } else {
        message.error("登录失败，请检查验证码是否正确");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bg-[url('/images/userBg.png')] bg-no-repeat bg-cover min-h-screen">
      <div className="container mx-auto pt-20 flex items-center justify-center">
        <div className="bg-white shadow-lg rounded-xl p-8 w-[500px]">
          <h1 className="text-2xl font-bold mb-6 flex items-center justify-center text-gray-800">
            欢迎来到检测认证公示中心
          </h1>

          {/* 分割线 */}
          <div className="border-b border-gray-300 w-full mb-6"></div>

          <Form
            form={form}
            name="login"
            onFinish={handleLogin}
            layout="vertical"
            size="large"
          >
            <Form.Item
              name="mobile"
              label="手机号"
              rules={[
                { required: true, message: "请输入手机号" },
                { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
              ]}
            >
              <Input
                prefix={<PhoneOutlined className="text-gray-400" />}
                placeholder="请输入手机号"
                maxLength={11}
              />
            </Form.Item>

            <Form.Item
              name="code"
              label="验证码"
              rules={[
                { required: true, message: "请输入验证码" },
                { len: 6, message: "验证码为6位数字" },
              ]}
            >
              <div className="flex gap-2">
                <Input
                  prefix={<LockOutlined className="text-gray-400" />}
                  placeholder="请输入验证码"
                  maxLength={6}
                  className="flex-1"
                />
                <Button
                  type="default"
                  onClick={handleSendSms}
                  loading={smsLoading}
                  disabled={countdown > 0}
                  className="min-w-[100px]"
                >
                  {countdown > 0 ? `${countdown}s` : "获取验证码"}
                </Button>
              </div>
            </Form.Item>

            <Form.Item className="mb-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <Checkbox
                    checked={agreed}
                    onChange={(e) => setAgreed(e.target.checked)}
                  />
                  <span className="ml-2 text-sm text-gray-600">
                    已阅读并同意
                  </span>
                </div>
                <div className="flex gap-1">
                  <Link
                    href="/login/user-agreement"
                    className="text-sm text-blue-500 hover:underline"
                  >
                    《用户协议》
                  </Link>
                  <span className="text-sm text-gray-600">和</span>
                  <Link
                    href="/login/privacy-policy"
                    className="text-sm text-blue-500 hover:underline"
                  >
                    《隐私政策》
                  </Link>
                </div>
              </div>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                className="w-full h-12 text-lg font-semibold"
              >
                登录
              </Button>
            </Form.Item>
          </Form>

          <div className="text-center mt-4">
            <p className="text-sm text-gray-500">
              未注册的手机号将自动创建账号
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
